package com.azusa.common.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

public class IOUtil {
	/**
	 * 从inputStream中读取字节流，转换成指定字符格式的字符串
	 * @param stream
	 * @param charset
	 * @return
	 * @throws IOException
	 */
	public static String getStreamAsString(InputStream stream, String charset) throws IOException {
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset));
			StringWriter writer = new StringWriter();

			char[] chars = new char[256];
			int count = 0;
			while ((count = reader.read(chars)) > 0) {
				writer.write(chars, 0, count);
			}

			return writer.toString();
		} finally {
			if (stream != null) {
				stream.close();
			}
		}
	}
	
	/**
	 * 指定一个文件，将文件中的内容读取成字符串
	 * @param filePath
	 * @return
	 */
	public static String getStringFromFile(String filePath){
		File srcFile = new File(filePath);
		String result = "";
		if(srcFile.exists() && !srcFile.isDirectory()){
			BufferedReader reader = null;
			try {
				reader = new BufferedReader(new FileReader(srcFile));
				StringBuilder sb = new StringBuilder();
				String temp = null;
				while((temp = reader.readLine()) != null){
					sb.append(temp);
				}
				result = sb.toString();
			} catch (IOException e) {
				return result ;
			}finally{
				try {
					reader.close();
				} catch (IOException e) {
					return result ;
				}
			}
		}
		
		return result;
	}
	
	/**
	 * 将文件中的数据按行读取,每一行为一个原数据
	 * emptyLine控制是否过滤掉文件中的空白行
	 * @param filePath
	 * @return
	 */
	public static List<String> getStringListByLine(String filePath,boolean emptyLine){
		File srcFile = new File(filePath);
		List<String> result = new ArrayList<String>();
		if(srcFile.exists() && !srcFile.isDirectory()){
			BufferedReader reader = null;
			try {
				reader = new BufferedReader(new FileReader(srcFile));
				String temp = null;
				while((temp = reader.readLine()) != null){
					if(emptyLine){
						if(!"".equals(temp)){
					        result.add(temp);
						}
					}else{
						result.add(temp);
					}
				}
			} catch (IOException e) {
				//do nothing,return empty List
				return result;
			}finally{
				try {
					reader.close();
				} catch (IOException e) {
					//do nothing,return empty List
					return result;
				}
			}
		}
		
		return result;
	}
}
